<template>
  <BasicModal
    title="模型分组"
    :destroy-on-close="true"
    width="60%"
    @ok="handleSubmit"
    @register="registerModal"
  >
    <BasicForm @register="register" />
  </BasicModal>
</template>
<script setup lang="ts">
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchemas } from './schemas';
  // eslint-disable-next-line prettier/prettier
  import { devSchemaGroupSave, devSchemaGroupUpdate, devSchemaGroupDetail } from '@/api/dev/schemaGroup';
  import { message } from 'ant-design-vue';
  import { ref } from 'vue';

  const emits = defineEmits(['register', 'success']);
  const currentRecord = ref();
  const [register, { validate, resetFields, setFieldsValue }] = useForm({
    schemas: formSchemas,
    showActionButtonGroup: false,
    labelWidth: 100,
  });
  /* eslint-disable prettier/prettier */
  const [registerModal, { changeLoading, changeOkLoading, closeModal }] = useModalInner((data) => {
    currentRecord.value = data.record;
    if(data.isUpdate){
      devSchemaGroupDetail({
        id: data.record.id,
      }).then((res) => {
        setFieldsValue(res);
      });
    } else {
      setFieldsValue(currentRecord.value);
    }
  });
  const handleSubmit = () => {
    validate().then((values) => {
      changeLoading(true);
      changeOkLoading(true);
      const submitApi = currentRecord.value?.id ? devSchemaGroupUpdate : devSchemaGroupSave;
      submitApi(values)
        .then(() => {
          message.success('提交成功');
          emits('success');
          resetFields();
          closeModal();
        })
        .catch(() => {
          message.success('提交失败');
        })
        .finally(() => {
          changeLoading(false);
          changeOkLoading(false);
        });
    });
  };
</script>
<style scoped lang="less">
  @import '@/assets/styles/common-form.less';
</style>
